package servlet.user;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/getUserInfoServlet")
public class GetUserInfoServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取当前登录用户的id
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            // 用户未登录，返回错误信息
            resp.setContentType("application/json;charset=UTF-8");
            // 使用Result封装统一结果
            Result result = Result.error("用户未登录");
            // 发送JSON格式数据给前端
            resp.getWriter().write(JSON.toJSONString(result));
            return;
        }

        int userId = currentUser.getUserId(); // 从 session 中获取当前用户ID

        // 获取用户信息
        User user = userService.getUserById(userId);

        resp.setContentType("application/json;charset=UTF-8");

        // 返回统一的响应格式
        Result result = Result.success(user);
        resp.getWriter().write(JSON.toJSONString(result));
    }
}
